package com.zzyl.common.utils;

import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;

public class AgeUtils {

    /**
     * 根据生日字符串计算年龄
     * @param birthDateStr 生日字符串，格式为 yyyy-MM-dd
     * @return 年龄（单位：岁），如果输入非法则返回 -1
     */
    public static int calculateAge(String birthDateStr) {
        try {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate birthDate = LocalDate.parse(birthDateStr, formatter);
            LocalDate now = LocalDate.now();

            if (birthDate.isAfter(now)) {
                return -1; // 出生日期在未来
            }

            return Period.between(birthDate, now).getYears();
        } catch (Exception e) {
            System.err.println("Invalid date format. Expected yyyy-MM-dd. Error: " + e.getMessage());
            return -1;
        }
    }
}